﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Xml.Linq;

namespace Zero.UControl.Demo.Views.UAdorner.Component
{
    public class DraggableAdorner : ElementDecoratorBase
    {
        private Point _startPoint;
        private bool _isDragging;

        public DraggableAdorner(UIElement adornedElement) : base(adornedElement)
        {
        }

        public override void Attach(UIElement element, Canvas canvas)
        {
            base.Attach(element, canvas);

            element.MouseLeftButtonDown += Element_MouseLeftButtonDown;
            element.MouseMove += Element_MouseMove;
            element.MouseLeftButtonUp += Element_MouseLeftButtonUp;
        }

        public override void Dettach(UIElement element)
        {
            base.Dettach(element);
            _element.MouseLeftButtonDown -= Element_MouseLeftButtonDown;
            _element.MouseMove -= Element_MouseMove;
            _element.MouseLeftButtonUp -= Element_MouseLeftButtonUp;
        }

        private void Element_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _startPoint = e.GetPosition(_canvas);
            _element.Focus();
            _element.CaptureMouse();
            _isDragging = true;
            e.Handled = true;
        }

        private void Element_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (!_isDragging) return;
            Point pos = e.GetPosition(_canvas);
            Vector delta = pos - _startPoint;
            _startPoint = pos;

            double left = Canvas.GetLeft(_element);
            double top = Canvas.GetTop(_element);

            Canvas.SetLeft(_element, left + delta.X);
            Canvas.SetTop(_element, top + delta.Y);
        }

        private void Element_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _isDragging = false;
            _element.ReleaseMouseCapture();
        }
    }
}
